import gtk
import nautilus
import urlparse
import logging

logger = logging.getLogger('dav-property-page')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler('/tmp/dav-property-page.log', 'w')
formatter = logging.Formatter('%(asctime)s %(levelname)-8s\n%(message)s\n',
                              '%a, %d %b %Y %H:%M:%S')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.propagate = 0


def log(msg):
    logger.info(msg)

def get_prop(conn, url, prop, depth=0):
    r = conn.getprops(url, prop[1], ns=prop[0], depth=depth)
    r.parse_multistatus()
    values = []
    for resp in r.msr.responses:
        values.append(resp.propstat[0].prop[prop].textof())
    return values

class DAVPropertyPage(nautilus.PropertyPageProvider):

    def __init__(self):
        pass

    def get_property_pages(self, files):

        if len(files) != 1:
            return

        file = files[0]

        if file.get_uri_scheme() not in ('dav', 'http', 'https', 'plone'):
            log(file.get_uri_scheme())
            return

        uri = file.get_uri()
        log(uri)
        subjects = 'None'

        try:
            subjects = self._get_subjects(uri)
        except:
            import traceback
            from cStringIO import StringIO
            s = StringIO()
            traceback.print_exc(file=s)
            log(s.getvalue())
        else:
            log(subjects)

        self.property_label = gtk.Label('Extra Information')
        self.property_label.show()

        self.hbox = gtk.HBox(0, False)
        self.hbox.show()

        label = gtk.Label('Subjects:')
        label.show()
        self.hbox.pack_start(label)

        self.value_label = gtk.Label()
        self.hbox.pack_start(self.value_label)

        self.value_label.set_text(subjects)
        self.value_label.show()

        return nautilus.PropertyPage("NautilusPython::dav_extra_info",
                                     self.property_label, self.hbox),

    def _get_subjects(self, uri):
        from WebDAV import davlib
        username = password = ''
        port = 80

        # XXX Humm... needs to check this 'secure dav' thing later
        if uri.startswith('dav'):
            # urlparse doesn't handle 'dav://' correctly
            uri =  uri.replace('dav', 'http')

        scheme, server_name, path = urlparse.urlparse(uri)[:3]

        log(scheme)
        log(path)
        log(server_name)

        if '@' in server_name:
            auth, server_name = server_name.split('@')
            if ':' in auth:
                username, password = auth.split(':')
            else:
                username = auth

        if ':' in server_name:
            server_name, port = server_name.split(':')
            port = int(port)

        log(server_name)
        log(str(port))
        log(scheme)

        conn = davlib.DAV(server_name, port, scheme=scheme)

        # XXX Needs to get the password from somewhere
        if not password:
            password = '123'
        log(username)
        log(password)
        conn.setauth(username, password)

        prop = (u'http://cmf.zope.org/propsets/dublincore',
                u'subject')

        return u', '.join(get_prop(conn, path, prop))
